<template>
  <div class="app-container">
    <!-- 来源提示 -->
    <el-alert
      v-if="fromResource"
      :title="`正在管理 ${fromResource} 的API Key`"
      type="info"
      :closable="false"
      show-icon
      style="margin-bottom: 15px;">
      <template slot="default">
        <el-button type="text" @click="clearFilter">查看全部</el-button>
      </template>
    </el-alert>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="Key名称" prop="keyName">
        <el-input
          v-model="queryParams.keyName"
          placeholder="请输入Key名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资源类型" prop="resourceType">
        <el-select v-model="queryParams.resourceType" placeholder="请选择资源类型" clearable>
          <el-option label="AI模型" value="ai_model" />
          <el-option label="TTS引擎" value="tts_engine" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="可用" value="available" />
          <el-option label="使用中" value="in_use" />
          <el-option label="限流" value="rate_limited" />
          <el-option label="禁用" value="disabled" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['tzai:api:keypool:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-refresh-right"
          size="mini"
          @click="handleRecover"
          v-hasPermi="['tzai:api:keypool:edit']"
        >恢复限流Key</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tzai:api:keypool:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="keyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="Key ID" align="center" prop="keyId" width="80" />
      <el-table-column label="Key名称" align="center" prop="keyName" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="资源类型" align="center" prop="resourceType" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.resourceType === 'ai_model'" type="primary">AI模型</el-tag>
          <el-tag v-else type="success">TTS引擎</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="资源ID" align="center" prop="resourceId" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.resourceType === 'ai_model'">
            {{ getAiModelName(scope.row.resourceId) }}
          </span>
          <span v-else>
            {{ getTtsEngineName(scope.row.resourceId) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="API Key" align="center" prop="apiKey" width="200" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ maskApiKey(scope.row.apiKey) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 'available'" type="success">可用</el-tag>
          <el-tag v-else-if="scope.row.status === 'in_use'" type="primary">使用中</el-tag>
          <el-tag v-else-if="scope.row.status === 'rate_limited'" type="warning">限流</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority" width="80" />
      <el-table-column label="并发数" align="center" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.currentConcurrency }} / {{ scope.row.maxConcurrency }}</span>
        </template>
      </el-table-column>
      <el-table-column label="成功率" align="center" prop="successRate" width="100">
        <template slot-scope="scope">
          <span :style="{color: scope.row.successRate >= 90 ? 'green' : (scope.row.successRate >= 70 ? 'orange' : 'red')}">
            {{ scope.row.successRate ? scope.row.successRate.toFixed(1) + '%' : '-' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="平均响应(ms)" align="center" prop="avgResponseTime" width="120">
        <template slot-scope="scope">
          {{ scope.row.avgResponseTime ? scope.row.avgResponseTime.toFixed(0) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="统计" align="center" width="120">
        <template slot-scope="scope">
          <el-tooltip placement="top">
            <div slot="content">
              总调用: {{ scope.row.totalCalls }}<br/>
              成功: {{ scope.row.successCalls }}<br/>
              失败: {{ scope.row.failedCalls }}
            </div>
            <span style="cursor: pointer;">
              {{ scope.row.totalCalls || 0 }} 次
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="限流重置时间" align="center" prop="rateLimitResetTime" width="160" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['tzai:api:keypool:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.status === 'disabled'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleEnable(scope.row)"
            v-hasPermi="['tzai:api:keypool:edit']"
          >启用</el-button>
          <el-button
            v-else
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleDisable(scope.row)"
            v-hasPermi="['tzai:api:keypool:edit']"
          >禁用</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tzai:api:keypool:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改API Key池对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="Key名称" prop="keyName">
          <el-input v-model="form.keyName" placeholder="请输入Key名称" />
        </el-form-item>
        <el-form-item label="资源类型" prop="resourceType">
          <el-select v-model="form.resourceType" placeholder="请选择资源类型" @change="handleResourceTypeChange">
            <el-option label="AI模型" value="ai_model" />
            <el-option label="TTS引擎" value="tts_engine" />
          </el-select>
        </el-form-item>
        <el-form-item label="资源" prop="resourceId">
          <el-select v-model="form.resourceId" placeholder="请选择资源">
            <template v-if="form.resourceType === 'ai_model'">
              <el-option
                v-for="model in aiModelList"
                :key="model.modelId"
                :label="model.modelName"
                :value="model.modelId"
              />
            </template>
            <template v-else>
              <el-option
                v-for="engine in ttsEngineList"
                :key="engine.engineId"
                :label="engine.engineName"
                :value="engine.engineId"
              />
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="API Key" prop="apiKey">
          <el-input v-model="form.apiKey" type="textarea" :rows="3" placeholder="请输入API Key" />
        </el-form-item>
        <el-form-item label="APP Key" prop="appKey">
          <el-input v-model="form.appKey" placeholder="可选，某些服务需要" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="form.priority" :min="0" :max="100" />
          <span style="margin-left: 10px; color: #999; font-size: 12px;">数值越大优先级越高</span>
        </el-form-item>
        <el-form-item label="最大并发数" prop="maxConcurrency">
          <el-input-number v-model="form.maxConcurrency" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="available">可用</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApiKeyPool, getApiKeyPool, addApiKeyPool, updateApiKeyPool, delApiKeyPool, recoverRateLimitedKeys } from "@/api/tzai/apiKeyPool";
import { listAIModel } from "@/api/tzai/aiModel";
import { listTTSEngine } from "@/api/tzai/ttsEngine";

export default {
  name: "ApiKeyPool",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // API Key池表格数据
      keyList: [],
      // AI模型列表
      aiModelList: [],
      // TTS引擎列表
      ttsEngineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 来源资源名称
      fromResource: null,
      // 来源资源ID
      fromResourceId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyName: null,
        resourceType: null,
        resourceId: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        keyName: [
          { required: true, message: "Key名称不能为空", trigger: "blur" }
        ],
        resourceType: [
          { required: true, message: "资源类型不能为空", trigger: "change" }
        ],
        resourceId: [
          { required: true, message: "资源不能为空", trigger: "change" }
        ],
        apiKey: [
          { required: true, message: "API Key不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    // 处理URL参数
    const { resourceType, resourceId, resourceName } = this.$route.query;
    if (resourceType && resourceId) {
      this.queryParams.resourceType = resourceType;
      this.queryParams.resourceId = parseInt(resourceId);
      this.fromResourceId = parseInt(resourceId);
      if (resourceName) {
        this.fromResource = resourceName;
      }
    }
    
    // 加载AI模型列表
    this.loadAIModelList();
    // 加载TTS引擎列表
    this.loadTTSEngineList();
    
    this.getList();
    // 定时刷新（每30秒）
    this.timer = setInterval(() => {
      this.getList();
    }, 30000);
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    /** 查询API Key池列表 */
    getList() {
      this.loading = true;
      listApiKeyPool(this.queryParams).then(response => {
        this.keyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        keyId: null,
        keyName: null,
        resourceType: 'ai_model',
        resourceId: null,
        apiKey: null,
        appKey: null,
        priority: 10,
        maxConcurrency: 10,
        status: 'available'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.keyId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 如果是从某个资源页面跳转过来的，自动设置资源信息
      if (this.fromResourceId && this.queryParams.resourceType) {
        this.form.resourceType = this.queryParams.resourceType;
        this.form.resourceId = this.fromResourceId;
      }
      this.open = true;
      this.title = "添加API Key";
    },
    /** 清除过滤条件 */
    clearFilter() {
      this.fromResource = null;
      this.fromResourceId = null;
      this.queryParams.resourceType = null;
      this.queryParams.resourceId = null;
      // 清除URL参数
      this.$router.replace({ path: this.$route.path });
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const keyId = row.keyId || this.ids
      getApiKeyPool(keyId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改API Key";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.keyId != null) {
            updateApiKeyPool(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addApiKeyPool(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 启用按钮操作 */
    handleEnable(row) {
      this.$modal.confirm('是否确认启用Key"' + row.keyName + '"?').then(() => {
        return updateApiKeyPool({
          keyId: row.keyId,
          status: 'available'
        });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("启用成功");
      }).catch(() => {});
    },
    /** 禁用按钮操作 */
    handleDisable(row) {
      this.$modal.confirm('是否确认禁用Key"' + row.keyName + '"?').then(() => {
        return updateApiKeyPool({
          keyId: row.keyId,
          status: 'disabled'
        });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("禁用成功");
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const keyIds = row.keyId || this.ids;
      this.$modal.confirm('是否确认删除Key ID为"' + keyIds + '"的数据项？').then(() => {
        return delApiKeyPool(keyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 恢复限流Key */
    handleRecover() {
      this.$modal.confirm('是否确认恢复所有限流状态的Key?').then(() => {
        return recoverRateLimitedKeys();
      }).then((response) => {
        this.getList();
        this.$modal.msgSuccess(response.msg);
      }).catch(() => {});
    },
    /** 资源类型改变 */
    handleResourceTypeChange() {
      this.form.resourceId = null;
    },
    /** 掩码显示API Key */
    maskApiKey(apiKey) {
      if (!apiKey || apiKey.length < 10) return apiKey;
      return apiKey.substring(0, 8) + '***' + apiKey.substring(apiKey.length - 4);
    },
    /** 加载AI模型列表 */
    loadAIModelList() {
      listAIModel({ pageNum: 1, pageSize: 100 }).then(response => {
        this.aiModelList = response.rows || [];
      });
    },
    /** 加载TTS引擎列表 */
    loadTTSEngineList() {
      listTTSEngine({ pageNum: 1, pageSize: 100 }).then(response => {
        this.ttsEngineList = response.rows || [];
      });
    },
    /** 获取AI模型名称 */
    getAiModelName(id) {
      const model = this.aiModelList.find(m => m.modelId === id);
      return model ? model.modelName : id;
    },
    /** 获取TTS引擎名称 */
    getTtsEngineName(id) {
      const engine = this.ttsEngineList.find(e => e.engineId === id);
      return engine ? engine.engineName : id;
    }
  }
};
</script>

